home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-9.10-netbook-remix-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / platform.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2009-11-11  |  37.6 KB  |  1,281 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. ''' This module tries to retrieve as much platform-identifying data as
  5.     possible. It makes this information available via function APIs.
  6.  
  7.     If called from the command line, it prints the platform
  8.     information concatenated as single string to stdout. The output
  9.     format is useable as part of a filename.
  10.  
  11. '''
  12. __copyright__ = '\n    Copyright (c) 1999-2000, Marc-Andre Lemburg; mailto:mal@lemburg.com\n    Copyright (c) 2000-2008, eGenix.com Software GmbH; mailto:info@egenix.com\n\n    Permission to use, copy, modify, and distribute this software and its\n    documentation for any purpose and without fee or royalty is hereby granted,\n    provided that the above copyright notice appear in all copies and that\n    both that copyright notice and this permission notice appear in\n    supporting documentation or portions thereof, including modifications,\n    that you make.\n\n    EGENIX.COM SOFTWARE GMBH DISCLAIMS ALL WARRANTIES WITH REGARD TO\n    THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND\n    FITNESS, IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL,\n    INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING\n    FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,\n    NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION\n    WITH THE USE OR PERFORMANCE OF THIS SOFTWARE !\n\n'
  13. __version__ = '1.0.6'
  14. import sys
  15. import string
  16. import os
  17. import re
  18. _libc_search = re.compile('(__libc_init)|(GLIBC_([0-9.]+))|(libc(_\\w+)?\\.so(?:\\.(\\d[0-9.]*))?)')
  19.  
  20. def libc_ver(executable = sys.executable, lib = '', version = '', chunksize = 2048):
  21.     ''' Tries to determine the libc version that the file executable
  22.         (which defaults to the Python interpreter) is linked against.
  23.  
  24.         Returns a tuple of strings (lib,version) which default to the
  25.         given parameters in case the lookup fails.
  26.  
  27.         Note that the function has intimate knowledge of how different
  28.         libc versions add symbols to the executable and thus is probably
  29.         only useable for executables compiled using gcc.
  30.  
  31.         The file is read and scanned in chunks of chunksize bytes.
  32.  
  33.     '''
  34.     if hasattr(os.path, 'realpath'):
  35.         executable = os.path.realpath(executable)
  36.     
  37.     f = open(executable, 'rb')
  38.     binary = f.read(chunksize)
  39.     pos = 0
  40.     while None:
  41.         m = _libc_search.search(binary, pos)
  42.         if not m:
  43.             binary = f.read(chunksize)
  44.             if not binary:
  45.                 break
  46.             
  47.             pos = 0
  48.             continue
  49.         
  50.         (libcinit, glibc, glibcversion, so, threads, soversion) = m.groups()
  51.         if libcinit and not lib:
  52.             lib = 'libc'
  53.         elif glibc:
  54.             if lib != 'glibc':
  55.                 lib = 'glibc'
  56.                 version = glibcversion
  57.             elif glibcversion > version:
  58.                 version = glibcversion
  59.             
  60.         elif so:
  61.             if lib != 'glibc':
  62.                 lib = 'libc'
  63.                 if soversion > version:
  64.                     version = soversion
  65.                 
  66.                 if threads and version[-len(threads):] != threads:
  67.                     version = version + threads
  68.                 
  69.             
  70.         
  71.         pos = m.end()
  72.         continue
  73.         return (lib, version)
  74.  
  75.  
  76. def _dist_try_harder(distname, version, id):
  77.     ''' Tries some special tricks to get the distribution
  78.         information in case the default method fails.
  79.  
  80.         Currently supports older SuSE Linux, Caldera OpenLinux and
  81.         Slackware Linux distributions.
  82.  
  83.     '''
  84.     if os.path.exists('/var/adm/inst-log/info'):
  85.         info = open('/var/adm/inst-log/info').readlines()
  86.         distname = 'SuSE'
  87.         for line in info:
  88.             tv = string.split(line)
  89.             if len(tv) == 2:
  90.                 (tag, value) = tv
  91.             
  92.             if tag == 'MIN_DIST_VERSION':
  93.                 version = string.strip(value)
  94.                 continue
  95.             len(tv) == 2
  96.             if tag == 'DIST_IDENT':
  97.                 values = string.split(value, '-')
  98.                 id = values[2]
  99.                 continue
  100.         
  101.         return (distname, version, id)
  102.     if os.path.isdir('/usr/lib/setup'):
  103.         verfiles = os.listdir('/usr/lib/setup')
  104.         for n in range(len(verfiles) - 1, -1, -1):
  105.             if verfiles[n][:14] != 'slack-version-':
  106.                 del verfiles[n]
  107.                 continue
  108.             None if os.path.exists('/etc/.installed') else os.path.exists('/var/adm/inst-log/info')
  109.         
  110.         if verfiles:
  111.             verfiles.sort()
  112.             distname = 'slackware'
  113.             version = verfiles[-1][14:]
  114.             return (distname, version, id)
  115.     
  116.     return (distname, version, id)
  117.  
  118. _release_filename = re.compile('(\\w+)[-_](release|version)')
  119. _lsb_release_version = re.compile('(.+) release ([\\d.]+)[^(]*(?:\\((.+)\\))?')
  120. _release_version = re.compile('([^0-9]+)(?: release )?([\\d.]+)[^(]*(?:\\((.+)\\))?')
  121. _supported_dists = ('SuSE', 'debian', 'fedora', 'redhat', 'centos', 'mandrake', 'mandriva', 'rocks', 'slackware', 'yellowdog', 'gentoo', 'UnitedLinux', 'turbolinux')
  122.  
  123. def _parse_release_file(firstline):
  124.     m = _lsb_release_version.match(firstline)
  125.     if m is not None:
  126.         return tuple(m.groups())
  127.     m = _release_version.match(firstline)
  128.     if m is not None:
  129.         return tuple(m.groups())
  130.     l = string.split(string.strip(firstline))
  131.     return ('', version, id)
  132.  
  133.  
  134. def _test_parse_release_file():
  135.     for input, output in ('SuSE Linux 9.3 (x86-64)', ('SuSE Linux ', '9.3', 'x86-64'))('SUSE LINUX 10.1 (X86-64)', ('SUSE LINUX ', '10.1', 'X86-64'))('SUSE LINUX 10.1 (i586)', ('SUSE LINUX ', '10.1', 'i586'))('Fedora Core release 5 (Bordeaux)', ('Fedora Core', '5', 'Bordeaux'))('Red Hat Linux release 8.0 (Psyche)', ('Red Hat Linux', '8.0', 'Psyche'))('Red Hat Linux release 9 (Shrike)', ('Red Hat Linux', '9', 'Shrike'))('Red Hat Enterprise Linux release 4 (Nahant)', ('Red Hat Enterprise Linux', '4', 'Nahant'))('CentOS release 4', ('CentOS', '4', None))('Rocks release 4.2.1 (Cydonia)', ('Rocks', '4.2.1', 'Cydonia')):
  136.         parsed = _parse_release_file(input)
  137.         if parsed != output:
  138.             print (input, parsed)
  139.             continue
  140.     
  141.  
  142. _distributor_id_file_re = re.compile('(?:DISTRIB_ID\\s*=)\\s*(.*)', re.I)
  143. _release_file_re = re.compile('(?:DISTRIB_RELEASE\\s*=)\\s*(.*)', re.I)
  144. _codename_file_re = re.compile('(?:DISTRIB_CODENAME\\s*=)\\s*(.*)', re.I)
  145.  
  146. def linux_distribution(distname = '', version = '', id = '', supported_dists = _supported_dists, full_distribution_name = 1):
  147.     ''' Tries to determine the name of the Linux OS distribution name.
  148.  
  149.         The function first looks for a distribution release file in
  150.         /etc and then reverts to _dist_try_harder() in case no
  151.         suitable files are found.
  152.  
  153.         supported_dists may be given to define the set of Linux
  154.         distributions to look for. It defaults to a list of currently
  155.         supported Linux distributions identified by their release file
  156.         name.
  157.  
  158.         If full_distribution_name is true (default), the full
  159.         distribution read from the OS is returned. Otherwise the short
  160.         name taken from supported_dists is used.
  161.  
  162.         Returns a tuple (distname,version,id) which default to the
  163.         args given as parameters.
  164.  
  165.     '''
  166.     
  167.     try:
  168.         etclsbrel = open('/etc/lsb-release', 'rU')
  169.         for line in etclsbrel:
  170.             m = _distributor_id_file_re.search(line)
  171.             if m:
  172.                 _u_distname = m.group(1).strip()
  173.             
  174.             m = _release_file_re.search(line)
  175.             if m:
  176.                 _u_version = m.group(1).strip()
  177.             
  178.             m = _codename_file_re.search(line)
  179.             if m:
  180.                 _u_id = m.group(1).strip()
  181.                 continue
  182.         
  183.         if _u_distname and _u_version:
  184.             return (_u_distname, _u_version, _u_id)
  185.     except (EnvironmentError, UnboundLocalError):
  186.         pass
  187.  
  188.     
  189.     try:
  190.         etc = os.listdir('/etc')
  191.     except os.error:
  192.         return (distname, version, id)
  193.  
  194.     etc.sort()
  195.     for file in etc:
  196.         m = _release_filename.match(file)
  197.         if m is not None:
  198.             (_distname, dummy) = m.groups()
  199.             if _distname in supported_dists:
  200.                 distname = _distname
  201.                 break
  202.             
  203.         _distname in supported_dists
  204.     else:
  205.         return _dist_try_harder(distname, version, id)
  206.     f = None('/etc/' + file, 'r')
  207.     firstline = f.readline()
  208.     f.close()
  209.     (_distname, _version, _id) = _parse_release_file(firstline)
  210.     if _distname and full_distribution_name:
  211.         distname = _distname
  212.     
  213.     if _version:
  214.         version = _version
  215.     
  216.     if _id:
  217.         id = _id
  218.     
  219.     return (distname, version, id)
  220.  
  221.  
  222. def dist(distname = '', version = '', id = '', supported_dists = _supported_dists):
  223.     ''' Tries to determine the name of the Linux OS distribution name.
  224.  
  225.         The function first looks for a distribution release file in
  226.         /etc and then reverts to _dist_try_harder() in case no
  227.         suitable files are found.
  228.  
  229.         Returns a tuple (distname,version,id) which default to the
  230.         args given as parameters.
  231.  
  232.     '''
  233.     return linux_distribution(distname, version, id, supported_dists = supported_dists, full_distribution_name = 0)
  234.  
  235.  
  236. class _popen:
  237.     """ Fairly portable (alternative) popen implementation.
  238.  
  239.         This is mostly needed in case os.popen() is not available, or
  240.         doesn't work as advertised, e.g. in Win9X GUI programs like
  241.         PythonWin or IDLE.
  242.  
  243.         Writing to the pipe is currently not supported.
  244.  
  245.     """
  246.     tmpfile = ''
  247.     pipe = None
  248.     bufsize = None
  249.     mode = 'r'
  250.     
  251.     def __init__(self, cmd, mode = 'r', bufsize = None):
  252.         if mode != 'r':
  253.             raise ValueError, 'popen()-emulation only supports read mode'
  254.         mode != 'r'
  255.         import tempfile
  256.         self.tmpfile = tmpfile = tempfile.mktemp()
  257.         os.system(cmd + ' > %s' % tmpfile)
  258.         self.pipe = open(tmpfile, 'rb')
  259.         self.bufsize = bufsize
  260.         self.mode = mode
  261.  
  262.     
  263.     def read(self):
  264.         return self.pipe.read()
  265.  
  266.     
  267.     def readlines(self):
  268.         if self.bufsize is not None:
  269.             return self.pipe.readlines()
  270.  
  271.     
  272.     def close(self, remove = os.unlink, error = os.error):
  273.         if self.pipe:
  274.             rc = self.pipe.close()
  275.         else:
  276.             rc = 255
  277.         if self.tmpfile:
  278.             
  279.             try:
  280.                 remove(self.tmpfile)
  281.             except error:
  282.                 pass
  283.             except:
  284.                 None<EXCEPTION MATCH>error
  285.             
  286.  
  287.         None<EXCEPTION MATCH>error
  288.         return rc
  289.  
  290.     __del__ = close
  291.  
  292.  
  293. def popen(cmd, mode = 'r', bufsize = None):
  294.     ''' Portable popen() interface.
  295.     '''
  296.     popen = None
  297.     if os.environ.get('OS', '') == 'Windows_NT':
  298.         
  299.         try:
  300.             import win32pipe
  301.         except ImportError:
  302.             pass
  303.  
  304.         popen = win32pipe.popen
  305.     
  306.     if popen is None:
  307.         if hasattr(os, 'popen'):
  308.             popen = os.popen
  309.             if sys.platform == 'win32':
  310.                 
  311.                 try:
  312.                     popen('')
  313.                 except os.error:
  314.                     popen = _popen
  315.                 except:
  316.                     None<EXCEPTION MATCH>os.error
  317.                 
  318.  
  319.             None<EXCEPTION MATCH>os.error
  320.         else:
  321.             popen = _popen
  322.     
  323.     if bufsize is None:
  324.         return popen(cmd, mode)
  325.     return popen(cmd, mode, bufsize)
  326.  
  327.  
  328. def _norm_version(version, build = ''):
  329.     ''' Normalize the version and build strings and return a single
  330.         version string using the format major.minor.build (or patchlevel).
  331.     '''
  332.     l = string.split(version, '.')
  333.     if build:
  334.         l.append(build)
  335.     
  336.     
  337.     try:
  338.         ints = map(int, l)
  339.     except ValueError:
  340.         strings = l
  341.  
  342.     strings = map(str, ints)
  343.     version = string.join(strings[:3], '.')
  344.     return version
  345.  
  346. _ver_output = re.compile('(?:([\\w ]+) ([\\w.]+) .*Version ([\\d.]+))')
  347.  
  348. def _syscmd_ver(system = '', release = '', version = '', supported_platforms = ('win32', 'win16', 'dos', 'os2')):
  349.     ''' Tries to figure out the OS version used and returns
  350.         a tuple (system,release,version).
  351.  
  352.         It uses the "ver" shell command for this which is known
  353.         to exists on Windows, DOS and OS/2. XXX Others too ?
  354.  
  355.         In case this fails, the given parameters are used as
  356.         defaults.
  357.  
  358.     '''
  359.     if sys.platform not in supported_platforms:
  360.         return (system, release, version)
  361.     for cmd in ('ver', 'command /c ver', 'cmd /c ver'):
  362.         
  363.         try:
  364.             pipe = popen(cmd)
  365.             info = pipe.read()
  366.             if pipe.close():
  367.                 raise os.error, 'command failed'
  368.             pipe.close()
  369.         except os.error:
  370.             sys.platform not in supported_platforms
  371.             why = sys.platform not in supported_platforms
  372.             continue
  373.             continue
  374.             except IOError:
  375.                 why = None
  376.                 continue
  377.                 continue
  378.             else:
  379.                 break
  380.         return (system, release, version)
  381.         info = string.strip(info)
  382.         m = _ver_output.match(info)
  383.  
  384.     return (system, release, version)
  385.  
  386.  
  387. def _win32_getvalue(key, name, default = ''):
  388.     ''' Read a value for name from the registry key.
  389.  
  390.         In case this fails, default is returned.
  391.  
  392.     '''
  393.     
  394.     try:
  395.         RegQueryValueEx = RegQueryValueEx
  396.         import win32api
  397.     except ImportError:
  398.         import _winreg
  399.         RegQueryValueEx = _winreg.QueryValueEx
  400.  
  401.     
  402.     try:
  403.         return RegQueryValueEx(key, name)
  404.     except:
  405.         return default
  406.  
  407.  
  408.  
  409. def win32_ver(release = '', version = '', csd = '', ptype = ''):
  410.     """ Get additional version information from the Windows Registry
  411.         and return a tuple (version,csd,ptype) referring to version
  412.         number, CSD level and OS type (multi/single
  413.         processor).
  414.  
  415.         As a hint: ptype returns 'Uniprocessor Free' on single
  416.         processor NT machines and 'Multiprocessor Free' on multi
  417.         processor machines. The 'Free' refers to the OS version being
  418.         free of debugging code. It could also state 'Checked' which
  419.         means the OS version uses debugging code, i.e. code that
  420.         checks arguments, ranges, etc. (Thomas Heller).
  421.  
  422.         Note: this function works best with Mark Hammond's win32
  423.         package installed, but also on Python 2.3 and later. It
  424.         obviously only runs on Win32 compatible platforms.
  425.  
  426.     """
  427.     
  428.     try:
  429.         import win32api
  430.         RegQueryValueEx = RegQueryValueEx
  431.         RegOpenKeyEx = RegOpenKeyEx
  432.         RegCloseKey = RegCloseKey
  433.         GetVersionEx = GetVersionEx
  434.         import win32api
  435.         HKEY_LOCAL_MACHINE = HKEY_LOCAL_MACHINE
  436.         VER_PLATFORM_WIN32_NT = VER_PLATFORM_WIN32_NT
  437.         VER_PLATFORM_WIN32_WINDOWS = VER_PLATFORM_WIN32_WINDOWS
  438.         VER_NT_WORKSTATION = VER_NT_WORKSTATION
  439.         import win32con
  440.     except ImportError:
  441.         
  442.         try:
  443.             sys.getwindowsversion
  444.         except AttributeError:
  445.             return (release, version, csd, ptype)
  446.  
  447.         import _winreg
  448.         GetVersionEx = sys.getwindowsversion
  449.         RegQueryValueEx = _winreg.QueryValueEx
  450.         RegOpenKeyEx = _winreg.OpenKeyEx
  451.         RegCloseKey = _winreg.CloseKey
  452.         HKEY_LOCAL_MACHINE = _winreg.HKEY_LOCAL_MACHINE
  453.         VER_PLATFORM_WIN32_WINDOWS = 1
  454.         VER_PLATFORM_WIN32_NT = 2
  455.         VER_NT_WORKSTATION = 1
  456.  
  457.     (maj, min, buildno, plat, csd) = GetVersionEx()
  458.     version = '%i.%i.%i' % (maj, min, buildno & 65535)
  459.     if csd[:13] == 'Service Pack ':
  460.         csd = 'SP' + csd[13:]
  461.     
  462.     if plat == VER_PLATFORM_WIN32_WINDOWS:
  463.         regkey = 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion'
  464.         if maj == 4:
  465.             if min == 0:
  466.                 release = '95'
  467.             elif min == 10:
  468.                 release = '98'
  469.             elif min == 90:
  470.                 release = 'Me'
  471.             else:
  472.                 release = 'postMe'
  473.         elif maj == 5:
  474.             release = '2000'
  475.         
  476.     elif plat == VER_PLATFORM_WIN32_NT:
  477.         regkey = 'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion'
  478.         if maj <= 4:
  479.             release = 'NT'
  480.         elif maj == 5:
  481.             if min == 0:
  482.                 release = '2000'
  483.             elif min == 1:
  484.                 release = 'XP'
  485.             elif min == 2:
  486.                 release = '2003Server'
  487.             else:
  488.                 release = 'post2003'
  489.         elif maj == 6:
  490.             if min == 0:
  491.                 
  492.                 try:
  493.                     productType = GetVersionEx(1)[8]
  494.                 except TypeError:
  495.                     release = 'Vista'
  496.  
  497.                 if productType == VER_NT_WORKSTATION:
  498.                     release = 'Vista'
  499.                 else:
  500.                     release = '2008Server'
  501.             else:
  502.                 release = 'post2008Server'
  503.         
  504.     elif not release:
  505.         release = '%i.%i' % (maj, min)
  506.     
  507.     return (release, version, csd, ptype)
  508.     
  509.     try:
  510.         keyCurVer = RegOpenKeyEx(HKEY_LOCAL_MACHINE, regkey)
  511.         RegQueryValueEx(keyCurVer, 'SystemRoot')
  512.     except:
  513.         return (release, version, csd, ptype)
  514.  
  515.     build = _win32_getvalue(keyCurVer, 'CurrentBuildNumber', ('', 1))[0]
  516.     ptype = _win32_getvalue(keyCurVer, 'CurrentType', (ptype, 1))[0]
  517.     version = _norm_version(version, build)
  518.     RegCloseKey(keyCurVer)
  519.     return (release, version, csd, ptype)
  520.  
  521.  
  522. def _mac_ver_lookup(selectors, default = None):
  523.     gestalt = gestalt
  524.     import gestalt
  525.     import MacOS
  526.     l = []
  527.     append = l.append
  528.     for selector in selectors:
  529.         
  530.         try:
  531.             append(gestalt(selector))
  532.         continue
  533.         except (RuntimeError, MacOS.Error):
  534.             append(default)
  535.             continue
  536.         
  537.  
  538.     
  539.     return l
  540.  
  541.  
  542. def _bcd2str(bcd):
  543.     return hex(bcd)[2:]
  544.  
  545.  
  546. def mac_ver(release = '', versioninfo = ('', '', ''), machine = ''):
  547.     """ Get MacOS version information and return it as tuple (release,
  548.         versioninfo, machine) with versioninfo being a tuple (version,
  549.         dev_stage, non_release_version).
  550.  
  551.         Entries which cannot be determined are set to the paramter values
  552.         which default to ''. All tuple entries are strings.
  553.  
  554.         Thanks to Mark R. Levinson for mailing documentation links and
  555.         code examples for this function. Documentation for the
  556.         gestalt() API is available online at:
  557.  
  558.            http://www.rgaros.nl/gestalt/
  559.  
  560.     """
  561.     
  562.     try:
  563.         import gestalt
  564.         import MacOS
  565.     except ImportError:
  566.         return (release, versioninfo, machine)
  567.  
  568.     (sysv, sysu, sysa) = _mac_ver_lookup(('sysv', 'sysu', 'sysa'))
  569.     if sysv:
  570.         major = (sysv & 65280) >> 8
  571.         minor = (sysv & 240) >> 4
  572.         patch = sysv & 15
  573.         if (major, minor) >= (10, 4):
  574.             (major, minor, patch) = _mac_ver_lookup(('sys1', 'sys2', 'sys3'))
  575.             release = '%i.%i.%i' % (major, minor, patch)
  576.         else:
  577.             release = '%s.%i.%i' % (_bcd2str(major), minor, patch)
  578.     
  579.     if sysu:
  580.         major = int((sysu & 0xFF000000L) >> 24)
  581.         minor = (sysu & 15728640) >> 20
  582.         bugfix = (sysu & 983040) >> 16
  583.         stage = (sysu & 65280) >> 8
  584.         nonrel = sysu & 255
  585.         version = '%s.%i.%i' % (_bcd2str(major), minor, bugfix)
  586.         nonrel = _bcd2str(nonrel)
  587.         stage = {
  588.             32: 'development',
  589.             64: 'alpha',
  590.             96: 'beta',
  591.             128: 'final' }.get(stage, '')
  592.         versioninfo = (version, stage, nonrel)
  593.     
  594.     if sysa:
  595.         machine = {
  596.             1: '68k',
  597.             2: 'PowerPC',
  598.             10: 'i386' }.get(sysa, '')
  599.     
  600.     return (release, versioninfo, machine)
  601.  
  602.  
  603. def _java_getprop(name, default):
  604.     System = System
  605.     import java.lang
  606.     
  607.     try:
  608.         value = System.getProperty(name)
  609.         if value is None:
  610.             return default
  611.         return value
  612.     except AttributeError:
  613.         return default
  614.  
  615.  
  616.  
  617. def java_ver(release = '', vendor = '', vminfo = ('', '', ''), osinfo = ('', '', '')):
  618.     """ Version interface for Jython.
  619.  
  620.         Returns a tuple (release,vendor,vminfo,osinfo) with vminfo being
  621.         a tuple (vm_name,vm_release,vm_vendor) and osinfo being a
  622.         tuple (os_name,os_version,os_arch).
  623.  
  624.         Values which cannot be determined are set to the defaults
  625.         given as parameters (which all default to '').
  626.  
  627.     """
  628.     
  629.     try:
  630.         import java.lang as java
  631.     except ImportError:
  632.         return (release, vendor, vminfo, osinfo)
  633.  
  634.     vendor = _java_getprop('java.vendor', vendor)
  635.     release = _java_getprop('java.version', release)
  636.     (vm_name, vm_release, vm_vendor) = vminfo
  637.     vm_name = _java_getprop('java.vm.name', vm_name)
  638.     vm_vendor = _java_getprop('java.vm.vendor', vm_vendor)
  639.     vm_release = _java_getprop('java.vm.version', vm_release)
  640.     vminfo = (vm_name, vm_release, vm_vendor)
  641.     (os_name, os_version, os_arch) = osinfo
  642.     os_arch = _java_getprop('java.os.arch', os_arch)
  643.     os_name = _java_getprop('java.os.name', os_name)
  644.     os_version = _java_getprop('java.os.version', os_version)
  645.     osinfo = (os_name, os_version, os_arch)
  646.     return (release, vendor, vminfo, osinfo)
  647.  
  648.  
  649. def system_alias(system, release, version):
  650.     ''' Returns (system,release,version) aliased to common
  651.         marketing names used for some systems.
  652.  
  653.         It also does some reordering of the information in some cases
  654.         where it would otherwise cause confusion.
  655.  
  656.     '''
  657.     if system == 'Rhapsody':
  658.         return ('MacOS X Server', system + release, version)
  659.     if system == 'SunOS':
  660.         if release < '5':
  661.             return (system, release, version)
  662.         l = string.split(release, '.')
  663.         if release < '6':
  664.             system = 'Solaris'
  665.         else:
  666.             system = 'Solaris'
  667.     elif system == 'IRIX64':
  668.         system = 'IRIX'
  669.         if version:
  670.             version = version + ' (64bit)'
  671.         else:
  672.             version = '64bit'
  673.     elif system in ('win32', 'win16'):
  674.         system = 'Windows'
  675.     
  676.     return (system, release, version)
  677.  
  678.  
  679. def _platform(*args):
  680.     ''' Helper to format the platform string in a filename
  681.         compatible format e.g. "system-version-machine".
  682.     '''
  683.     platform = string.join(map(string.strip, filter(len, args)), '-')
  684.     replace = string.replace
  685.     platform = replace(platform, ' ', '_')
  686.     platform = replace(platform, '/', '-')
  687.     platform = replace(platform, '\\', '-')
  688.     platform = replace(platform, ':', '-')
  689.     platform = replace(platform, ';', '-')
  690.     platform = replace(platform, '"', '-')
  691.     platform = replace(platform, '(', '-')
  692.     platform = replace(platform, ')', '-')
  693.     platform = replace(platform, 'unknown', '')
  694.     while None:
  695.         cleaned = replace(platform, '--', '-')
  696.         if cleaned == platform:
  697.             break
  698.         
  699.         platform = cleaned
  700.         continue
  701.         while platform[-1] == '-':
  702.             platform = platform[:-1]
  703.         return platform
  704.  
  705.  
  706. def _node(default = ''):
  707.     ''' Helper to determine the node name of this machine.
  708.     '''
  709.     
  710.     try:
  711.         import socket
  712.     except ImportError:
  713.         return default
  714.  
  715.     
  716.     try:
  717.         return socket.gethostname()
  718.     except socket.error:
  719.         return default
  720.  
  721.  
  722. if not hasattr(os.path, 'abspath'):
  723.     
  724.     def _abspath(path, isabs = os.path.isabs, join = os.path.join, getcwd = os.getcwd, normpath = os.path.normpath):
  725.         if not isabs(path):
  726.             path = join(getcwd(), path)
  727.         
  728.         return normpath(path)
  729.  
  730. else:
  731.     _abspath = os.path.abspath
  732.  
  733. def _follow_symlinks(filepath):
  734.     ''' In case filepath is a symlink, follow it until a
  735.         real file is reached.
  736.     '''
  737.     filepath = _abspath(filepath)
  738.     while os.path.islink(filepath):
  739.         filepath = os.path.normpath(os.path.join(os.path.dirname(filepath), os.readlink(filepath)))
  740.     return filepath
  741.  
  742.  
  743. def _syscmd_uname(option, default = ''):
  744.     """ Interface to the system's uname command.
  745.     """
  746.     if sys.platform in ('dos', 'win32', 'win16', 'os2'):
  747.         return default
  748.     
  749.     try:
  750.         f = os.popen('uname %s 2> /dev/null' % option)
  751.     except (AttributeError, os.error):
  752.         sys.platform in ('dos', 'win32', 'win16', 'os2')
  753.         sys.platform in ('dos', 'win32', 'win16', 'os2')
  754.         return default
  755.  
  756.     output = string.strip(f.read())
  757.     rc = f.close()
  758.     if not output or rc:
  759.         return default
  760.     return output
  761.  
  762.  
  763. def _syscmd_file(target, default = ''):
  764.     """ Interface to the system's file command.
  765.  
  766.         The function uses the -b option of the file command to have it
  767.         ommit the filename in its output and if possible the -L option
  768.         to have the command follow symlinks. It returns default in
  769.         case the command should fail.
  770.  
  771.     """
  772.     if sys.platform in ('dos', 'win32', 'win16', 'os2'):
  773.         return default
  774.     target = _follow_symlinks(target)
  775.     
  776.     try:
  777.         f = os.popen('file "%s" 2> /dev/null' % target)
  778.     except (AttributeError, os.error):
  779.         sys.platform in ('dos', 'win32', 'win16', 'os2')
  780.         sys.platform in ('dos', 'win32', 'win16', 'os2')
  781.         return default
  782.  
  783.     output = string.strip(f.read())
  784.     rc = f.close()
  785.     if not output or rc:
  786.         return default
  787.     return output
  788.  
  789. _default_architecture = {
  790.     'win32': ('', 'WindowsPE'),
  791.     'win16': ('', 'Windows'),
  792.     'dos': ('', 'MSDOS') }
  793. _architecture_split = re.compile('[\\s,]').split
  794.  
  795. def architecture(executable = sys.executable, bits = '', linkage = ''):
  796.     ''' Queries the given executable (defaults to the Python interpreter
  797.         binary) for various architecture information.
  798.  
  799.         Returns a tuple (bits,linkage) which contains information about
  800.         the bit architecture and the linkage format used for the
  801.         executable. Both values are returned as strings.
  802.  
  803.         Values that cannot be determined are returned as given by the
  804.         parameter presets. If bits is given as \'\', the sizeof(pointer)
  805.         (or sizeof(long) on Python version < 1.5.2) is used as
  806.         indicator for the supported pointer size.
  807.  
  808.         The function relies on the system\'s "file" command to do the
  809.         actual work. This is available on most if not all Unix
  810.         platforms. On some non-Unix platforms where the "file" command
  811.         does not exist and the executable is set to the Python interpreter
  812.         binary defaults from _default_architecture are used.
  813.  
  814.     '''
  815.     if not bits:
  816.         import struct
  817.         
  818.         try:
  819.             size = struct.calcsize('P')
  820.         except struct.error:
  821.             size = struct.calcsize('l')
  822.  
  823.         bits = str(size * 8) + 'bit'
  824.     
  825.     if executable:
  826.         output = _syscmd_file(executable, '')
  827.     else:
  828.         output = ''
  829.     if not output and executable == sys.executable:
  830.         if _default_architecture.has_key(sys.platform):
  831.             (b, l) = _default_architecture[sys.platform]
  832.             if b:
  833.                 bits = b
  834.             
  835.             if l:
  836.                 linkage = l
  837.             
  838.         
  839.         return (bits, linkage)
  840.     fileout = _architecture_split(output)[1:]
  841.     if 'executable' not in fileout:
  842.         return (bits, linkage)
  843.     if '32-bit' in fileout:
  844.         bits = '32bit'
  845.     elif 'N32' in fileout:
  846.         bits = 'n32bit'
  847.     elif '64-bit' in fileout:
  848.         bits = '64bit'
  849.     
  850.     if 'ELF' in fileout:
  851.         linkage = 'ELF'
  852.     elif 'PE' in fileout:
  853.         if 'Windows' in fileout:
  854.             linkage = 'WindowsPE'
  855.         else:
  856.             linkage = 'PE'
  857.     elif 'COFF' in fileout:
  858.         linkage = 'COFF'
  859.     elif 'MS-DOS' in fileout:
  860.         linkage = 'MSDOS'
  861.     
  862.     return (bits, linkage)
  863.  
  864. _uname_cache = None
  865.  
  866. def uname():
  867.     """ Fairly portable uname interface. Returns a tuple
  868.         of strings (system,node,release,version,machine,processor)
  869.         identifying the underlying platform.
  870.  
  871.         Note that unlike the os.uname function this also returns
  872.         possible processor information as an additional tuple entry.
  873.  
  874.         Entries which cannot be determined are set to ''.
  875.  
  876.     """
  877.     global _uname_cache
  878.     no_os_uname = 0
  879.     if _uname_cache is not None:
  880.         return _uname_cache
  881.     processor = ''
  882.     
  883.     try:
  884.         (system, node, release, version, machine) = os.uname()
  885.     except AttributeError:
  886.         _uname_cache is not None
  887.         _uname_cache is not None
  888.         no_os_uname = 1
  889.     except:
  890.         _uname_cache is not None
  891.  
  892.     if no_os_uname or not filter(None, (system, node, release, version, machine)):
  893.         if no_os_uname:
  894.             system = sys.platform
  895.             release = ''
  896.             version = ''
  897.             node = _node()
  898.             machine = ''
  899.         
  900.         use_syscmd_ver = 1
  901.         if system == 'win32':
  902.             (release, version, csd, ptype) = win32_ver()
  903.             if release and version:
  904.                 use_syscmd_ver = 0
  905.             
  906.             if not machine:
  907.                 machine = os.environ.get('PROCESSOR_ARCHITECTURE', '')
  908.             
  909.             if not processor:
  910.                 processor = os.environ.get('PROCESSOR_IDENTIFIER', machine)
  911.             
  912.         
  913.         if use_syscmd_ver:
  914.             (system, release, version) = _syscmd_ver(system)
  915.             if system == 'Microsoft Windows':
  916.                 system = 'Windows'
  917.             elif system == 'Microsoft' and release == 'Windows':
  918.                 system = 'Windows'
  919.                 if '6.0' == version[:3]:
  920.                     release = 'Vista'
  921.                 else:
  922.                     release = ''
  923.             
  924.         
  925.         if system in ('win32', 'win16'):
  926.             if not version:
  927.                 if system == 'win32':
  928.                     version = '32bit'
  929.                 else:
  930.                     version = '16bit'
  931.             
  932.             system = 'Windows'
  933.         elif system[:4] == 'java':
  934.             (release, vendor, vminfo, osinfo) = java_ver()
  935.             system = 'Java'
  936.             version = string.join(vminfo, ', ')
  937.             if not version:
  938.                 version = vendor
  939.             
  940.         elif os.name == 'mac':
  941.             (version, stage, nonrel) = (release,)
  942.             machine = mac_ver()
  943.             system = 'MacOS'
  944.         
  945.     
  946.     if system == 'OpenVMS':
  947.         if not release or release == '0':
  948.             release = version
  949.             version = ''
  950.         
  951.         
  952.         try:
  953.             import vms_lib
  954.         except ImportError:
  955.             pass
  956.  
  957.         (csid, cpu_number) = vms_lib.getsyi('SYI$_CPU', 0)
  958.         if cpu_number >= 128:
  959.             processor = 'Alpha'
  960.         else:
  961.             processor = 'VAX'
  962.     
  963.     if not processor:
  964.         processor = _syscmd_uname('-p', '')
  965.     
  966.     if system == 'unknown':
  967.         system = ''
  968.     
  969.     if node == 'unknown':
  970.         node = ''
  971.     
  972.     if release == 'unknown':
  973.         release = ''
  974.     
  975.     if version == 'unknown':
  976.         version = ''
  977.     
  978.     if machine == 'unknown':
  979.         machine = ''
  980.     
  981.     if processor == 'unknown':
  982.         processor = ''
  983.     
  984.     if system == 'Microsoft' and release == 'Windows':
  985.         system = 'Windows'
  986.         release = 'Vista'
  987.     
  988.     _uname_cache = (system, node, release, version, machine, processor)
  989.     return _uname_cache
  990.  
  991.  
  992. def system():
  993.     """ Returns the system/OS name, e.g. 'Linux', 'Windows' or 'Java'.
  994.  
  995.         An empty string is returned if the value cannot be determined.
  996.  
  997.     """
  998.     return uname()[0]
  999.  
  1000.  
  1001. def node():
  1002.     """ Returns the computer's network name (which may not be fully
  1003.         qualified)
  1004.  
  1005.         An empty string is returned if the value cannot be determined.
  1006.  
  1007.     """
  1008.     return uname()[1]
  1009.  
  1010.  
  1011. def release():
  1012.     """ Returns the system's release, e.g. '2.2.0' or 'NT'
  1013.  
  1014.         An empty string is returned if the value cannot be determined.
  1015.  
  1016.     """
  1017.     return uname()[2]
  1018.  
  1019.  
  1020. def version():
  1021.     """ Returns the system's release version, e.g. '#3 on degas'
  1022.  
  1023.         An empty string is returned if the value cannot be determined.
  1024.  
  1025.     """
  1026.     return uname()[3]
  1027.  
  1028.  
  1029. def machine():
  1030.     """ Returns the machine type, e.g. 'i386'
  1031.  
  1032.         An empty string is returned if the value cannot be determined.
  1033.  
  1034.     """
  1035.     return uname()[4]
  1036.  
  1037.  
  1038. def processor():
  1039.     """ Returns the (true) processor name, e.g. 'amdk6'
  1040.  
  1041.         An empty string is returned if the value cannot be
  1042.         determined. Note that many platforms do not provide this
  1043.         information or simply return the same value as for machine(),
  1044.         e.g.  NetBSD does this.
  1045.  
  1046.     """
  1047.     return uname()[5]
  1048.  
  1049. _sys_version_parser = re.compile('([\\w.+]+)\\s*\\(#?([^,]+),\\s*([\\w ]+),\\s*([\\w :]+)\\)\\s*\\[([^\\]]+)\\]?')
  1050. _jython_sys_version_parser = re.compile('([\\d\\.]+)')
  1051. _ironpython_sys_version_parser = re.compile('IronPython\\s*([\\d\\.]+)(?: \\(([\\d\\.]+)\\))? on (.NET [\\d\\.]+)')
  1052. _sys_version_cache = { }
  1053.  
  1054. def _sys_version(sys_version = None):
  1055.     """ Returns a parsed version of Python's sys.version as tuple
  1056.         (name, version, branch, revision, buildno, builddate, compiler)
  1057.         referring to the Python implementation name, version, branch,
  1058.         revision, build number, build date/time as string and the compiler
  1059.         identification string.
  1060.  
  1061.         Note that unlike the Python sys.version, the returned value
  1062.         for the Python version will always include the patchlevel (it
  1063.         defaults to '.0').
  1064.  
  1065.         The function returns empty strings for tuple entries that
  1066.         cannot be determined.
  1067.  
  1068.         sys_version may be given to parse an alternative version
  1069.         string, e.g. if the version was read from a different Python
  1070.         interpreter.
  1071.  
  1072.     """
  1073.     if sys_version is None:
  1074.         sys_version = sys.version
  1075.     
  1076.     result = _sys_version_cache.get(sys_version, None)
  1077.     if result is not None:
  1078.         return result
  1079.     if sys_version[:10] == 'IronPython':
  1080.         name = 'IronPython'
  1081.         match = _ironpython_sys_version_parser.match(sys_version)
  1082.         if match is None:
  1083.             raise ValueError('failed to parse IronPython sys.version: %s' % repr(sys_version))
  1084.         match is None
  1085.         (version, alt_version, compiler) = match.groups()
  1086.         branch = ''
  1087.         revision = ''
  1088.         buildno = ''
  1089.         builddate = ''
  1090.     elif sys.platform[:4] == 'java':
  1091.         name = 'Jython'
  1092.         match = _jython_sys_version_parser.match(sys_version)
  1093.         if match is None:
  1094.             raise ValueError('failed to parse Jython sys.version: %s' % repr(sys_version))
  1095.         match is None
  1096.         (version,) = match.groups()
  1097.         branch = ''
  1098.         revision = ''
  1099.         compiler = sys.platform
  1100.         buildno = ''
  1101.         builddate = ''
  1102.     else:
  1103.         match = _sys_version_parser.match(sys_version)
  1104.         if match is None:
  1105.             raise ValueError('failed to parse CPython sys.version: %s' % repr(sys_version))
  1106.         match is None
  1107.         (version, buildno, builddate, buildtime, compiler) = match.groups()
  1108.         if hasattr(sys, 'subversion'):
  1109.             (name, branch, revision) = sys.subversion
  1110.         else:
  1111.             name = 'CPython'
  1112.             branch = ''
  1113.             revision = ''
  1114.         builddate = builddate + ' ' + buildtime
  1115.     l = string.split(version, '.')
  1116.     if len(l) == 2:
  1117.         l.append('0')
  1118.         version = string.join(l, '.')
  1119.     
  1120.     result = (name, version, branch, revision, buildno, builddate, compiler)
  1121.     _sys_version_cache[sys_version] = result
  1122.     return result
  1123.  
  1124.  
  1125. def _test_sys_version():
  1126.     _sys_version_cache.clear()
  1127.     for input, output in (('2.4.3 (#1, Jun 21 2006, 13:54:21) \n[GCC 3.3.4 (pre 3.3.5 20040809)]', ('CPython', '2.4.3', '', '', '1', 'Jun 21 2006 13:54:21', 'GCC 3.3.4 (pre 3.3.5 20040809)')), ('IronPython 1.0.60816 on .NET 2.0.50727.42', ('IronPython', '1.0.60816', '', '', '', '', '.NET 2.0.50727.42')), ('IronPython 1.0 (1.0.61005.1977) on .NET 2.0.50727.42', ('IronPython', '1.0.0', '', '', '', '', '.NET 2.0.50727.42'))):
  1128.         parsed = _sys_version(input)
  1129.         if parsed != output:
  1130.             print (input, parsed)
  1131.             continue
  1132.     
  1133.  
  1134.  
  1135. def python_implementation():
  1136.     """ Returns a string identifying the Python implementation.
  1137.  
  1138.         Currently, the following implementations are identified:
  1139.         'CPython' (C implementation of Python),
  1140.         'IronPython' (.NET implementation of Python),
  1141.         'Jython' (Java implementation of Python).
  1142.  
  1143.     """
  1144.     return _sys_version()[0]
  1145.  
  1146.  
  1147. def python_version():
  1148.     """ Returns the Python version as string 'major.minor.patchlevel'
  1149.  
  1150.         Note that unlike the Python sys.version, the returned value
  1151.         will always include the patchlevel (it defaults to 0).
  1152.  
  1153.     """
  1154.     return _sys_version()[1]
  1155.  
  1156.  
  1157. def python_version_tuple():
  1158.     ''' Returns the Python version as tuple (major, minor, patchlevel)
  1159.         of strings.
  1160.  
  1161.         Note that unlike the Python sys.version, the returned value
  1162.         will always include the patchlevel (it defaults to 0).
  1163.  
  1164.     '''
  1165.     return tuple(string.split(_sys_version()[1], '.'))
  1166.  
  1167.  
  1168. def python_branch():
  1169.     ''' Returns a string identifying the Python implementation
  1170.         branch.
  1171.  
  1172.         For CPython this is the Subversion branch from which the
  1173.         Python binary was built.
  1174.  
  1175.         If not available, an empty string is returned.
  1176.  
  1177.     '''
  1178.     return _sys_version()[2]
  1179.  
  1180.  
  1181. def python_revision():
  1182.     ''' Returns a string identifying the Python implementation
  1183.         revision.
  1184.  
  1185.         For CPython this is the Subversion revision from which the
  1186.         Python binary was built.
  1187.  
  1188.         If not available, an empty string is returned.
  1189.  
  1190.     '''
  1191.     return _sys_version()[3]
  1192.  
  1193.  
  1194. def python_build():
  1195.     ''' Returns a tuple (buildno, builddate) stating the Python
  1196.         build number and date as strings.
  1197.  
  1198.     '''
  1199.     return _sys_version()[4:6]
  1200.  
  1201.  
  1202. def python_compiler():
  1203.     ''' Returns a string identifying the compiler used for compiling
  1204.         Python.
  1205.  
  1206.     '''
  1207.     return _sys_version()[6]
  1208.  
  1209. _platform_cache = { }
  1210.  
  1211. def platform(aliased = 0, terse = 0):
  1212.     ''' Returns a single string identifying the underlying platform
  1213.         with as much useful information as possible (but no more :).
  1214.  
  1215.         The output is intended to be human readable rather than
  1216.         machine parseable. It may look different on different
  1217.         platforms and this is intended.
  1218.  
  1219.         If "aliased" is true, the function will use aliases for
  1220.         various platforms that report system names which differ from
  1221.         their common names, e.g. SunOS will be reported as
  1222.         Solaris. The system_alias() function is used to implement
  1223.         this.
  1224.  
  1225.         Setting terse to true causes the function to return only the
  1226.         absolute minimum information needed to identify the platform.
  1227.  
  1228.     '''
  1229.     result = _platform_cache.get((aliased, terse), None)
  1230.     if result is not None:
  1231.         return result
  1232.     (system, node, release, version, machine, processor) = uname()
  1233.     if machine == processor:
  1234.         processor = ''
  1235.     
  1236.     if aliased:
  1237.         (system, release, version) = system_alias(system, release, version)
  1238.     
  1239.     if system == 'Windows':
  1240.         (rel, vers, csd, ptype) = win32_ver(version)
  1241.         if terse:
  1242.             platform = _platform(system, release)
  1243.         else:
  1244.             platform = _platform(system, release, version, csd)
  1245.     elif system in ('Linux',):
  1246.         (distname, distversion, distid) = dist('')
  1247.         if distname and not terse:
  1248.             platform = _platform(system, release, machine, processor, 'with', distname, distversion, distid)
  1249.         else:
  1250.             (libcname, libcversion) = libc_ver(sys.executable)
  1251.             platform = _platform(system, release, machine, processor, 'with', libcname + libcversion)
  1252.     elif system == 'Java':
  1253.         (os_name, os_version, os_arch) = (r, v, vminfo)
  1254.         if terse or not os_name:
  1255.             platform = _platform(system, release, version)
  1256.         else:
  1257.             platform = _platform(system, release, version, 'on', os_name, os_version, os_arch)
  1258.     elif system == 'MacOS':
  1259.         if terse:
  1260.             platform = _platform(system, release)
  1261.         else:
  1262.             platform = _platform(system, release, machine)
  1263.     elif terse:
  1264.         platform = _platform(system, release)
  1265.     else:
  1266.         (bits, linkage) = architecture(sys.executable)
  1267.         platform = _platform(system, release, machine, processor, bits, linkage)
  1268.     _platform_cache[(aliased, terse)] = platform
  1269.     return platform
  1270.  
  1271. if __name__ == '__main__':
  1272.     if not 'terse' in sys.argv:
  1273.         pass
  1274.     terse = '--terse' in sys.argv
  1275.     if 'nonaliased' not in sys.argv:
  1276.         pass
  1277.     aliased = '--nonaliased' not in sys.argv
  1278.     print platform(aliased, terse)
  1279.     sys.exit(0)
  1280.  
  1281.